<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Main extends Page {

    public function action_index()
    {
        $this->add_styles(array(
            'css_pirobox/style_2/style',
        ));
        $this->add_scripts(array(
            'pirobox_extended_min',
            'pager',
        ));

        if (HTTP_Request::POST == $this->request->method())
        {
            if (isset($_FILES))
            {
                $upload = Validation::factory($_FILES)
                    ->rules('userfile', array(
                    array('not_empty'),
                    array('Upload::not_empty'),
                    array('Upload::valid'),
                    array('Upload::type', array(':value', array(
                        'png',
                        'jpg',
                        'jpeg'
                    ))),
                    array('Upload::size', array(':value', '2M'))
                ));

                if ($upload->check())
                {
                    $ext = pathinfo($upload['userfile']['name'], PATHINFO_EXTENSION);
                    $orig_filename = substr($unique = md5(uniqid(rand(),1)), 0, -20).'.'.$ext;
                    $filepath = Upload::save($_FILES['userfile'], $orig_filename, $this->upload_original);

                    $thumb = Image::factory($filepath);
                    $thumb->resize($this->main_config->get('thumb_width'), $this->main_config->get('thumb_height'), Image::NONE);
                    $thumb_filename = 'tumb_'.$orig_filename;
                    $thumb_path = $this->upload_thumbs.'/'.$thumb_filename;
                    if ($thumb->save($thumb_path))
                    {
                        $image = ORM::factory('image');
                        $image->original_name = $orig_filename;
                        $image->thumbnail_name = $thumb_filename;
                        $image->size = $upload['userfile']['size'];
                        $image->description = array_key_exists('description', $this->request->post()) ? $this->request->post('description') : "No description";
                        $image->save();
                    }
                }
            }
        }

        $view = View::factory('main/index');
        $view->set('images', ORM::factory('image')->find_all());
        $this->template->content = $view;
    }
}